package com.kgcx.organization.rabbitmq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.kgcx.common.client.order.OrderClient;
import com.kgcx.common.client.schedule.pojo.ScheduleRecord;
import com.kgcx.common.constant.Cons;
import com.kgcx.common.rabbitmq.consts.QueueConst;
import com.kgcx.core.utils.JsonUtil;
import com.kgcx.organization.service.DriverService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 行程结束，或者司机被改派时，解锁司机，状态变更
 */
@Component
public class DriverUnlockDriverConsumer {
    private static final Logger LOG = LoggerFactory.getLogger(DriverUnlockDriverConsumer.class);

    @Autowired
    private DriverService driverService;
    @Autowired
    private OrderClient orderClient;

    @RabbitListener(queues = QueueConst.DRIVER_UNLOCK_DRIVER, errorHandler = "custRabbitListenerErrorHandler")
    public void precessUserStatus(String json) {
        LOG.info("收到解锁司机的MQ消息。\n" + json);

        ScheduleRecord scheduleRecord = JSONObject.parseObject(json, ScheduleRecord.class);
        if (null == scheduleRecord.getDriver_id()) {
            return;
        }

        updateDriverState(scheduleRecord.getDriver_id());
    }

    /**
     * @param driver_id
     */
    private void updateDriverState(Long driver_id) {
        Integer driverState = Cons.DRIVER_STATE_ON; // 默认切换为上线
        try {
            // 检查司机是否能服务
            Integer data = orderClient.checkDriverServeState(driver_id);
            LOG.info("检查司机是否能服务结果：" + JsonUtil.toString(data));
            if (data == null) {
                driverState = Cons.DRIVER_STATE_OFF; // 不能服务时强制下线
            }
        } catch (Exception e) {
            driverState = Cons.DRIVER_STATE_ON;
            LOG.error("司机状态切换为上线，检查司机是否能服务失败！", e);
        }
        LOG.info("最终将司机状态改为：" + driverState);
        driverService.updateDriverState(driver_id, driverState, null, null);
        driverService.notifyDriverState(driver_id, driverState);
    }

}
